"""
 -*- coding: utf-8-*-
 @File: api_owner_mgt.py
 @Author: chen
 @time: 2024/01/13/ 11:17
"""
import jsonpath

from api_test.api_po_test.api_business.api_base import BaseApi


class OwnerMgtApi(BaseApi):
    def create_owner(self, first_name, last_name, address, city, telephone):
        """注册owner接口"""
        self.logger.info(f"创建宠物主人：【{first_name} {last_name}】")
        path = "/petclinic/api/owners"
        data = {
            "firstName": first_name,
            "lastName": last_name,
            "address": address,
            "city": city,
            "telephone": telephone
        }
        resp = self.send("post", path, json=data)
        return resp.json()

    def owner_list(self):
        self.logger.info("查询宠物主人列表信息")
        path = "/petclinic/api/owners"
        resp = self.send("get", path)
        return resp.json()

    def get_owner_id(self, first_name, last_name):
        resp = self.owner_list()
        self.logger.info(f"获取宠物主人【{first_name} {last_name}】的id")
        expr = f"$..[?(@.firstName=='{first_name}' and @.lastName=='{last_name}')].id"
        result = jsonpath.jsonpath(resp, expr)
        if result:
            self.logger.info(f"获取宠物主人【{first_name} {last_name}】的id--->成功")
            return result[-1]
        else:
            self.logger.error(f"获取宠物主人【{first_name} {last_name}】的id--->失败")
            return None

    def owner_info(self, first_name, last_name):
        owner_id = self.get_owner_id(first_name, last_name)
        self.logger.info(f"获取宠物主人【{first_name} {last_name}】的信息")
        path = f"/petclinic/api/owners/{owner_id}"
        resp = self.send("get", path)
        return resp.json()

    def owner_is_exist(self, first_name, last_name):
        resp = self.owner_list().json()
        self.logger.info(f"判断宠物主人【{first_name} {last_name}】是否存在")
        expr = f"$..[?(@.firstName=='{first_name}' and @.lastName=='{last_name}')].id"
        result = jsonpath.jsonpath(resp, expr)
        if result:
            self.logger.info(f"判断宠物主人【{first_name} {last_name}】--->存在")
            return True
        else:
            self.logger.info(f"判断宠物主人【{first_name} {last_name}】--->不存在")
            return False


if __name__ == '__main__':
    o0 = OwnerMgtApi()
    first_name0 = "murong"
    last_name0 = "shaozong"
    address0 = "guanggu"
    city0 = "wuhan"
    telephone0 = "1591234567"
    print(o0.get_owner_id(first_name0, last_name0))
